﻿using System;
using System.IO;
using System.Net;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

namespace AppFuscator
{
    internal class WebRequest
    {
        public CookieContainer cookieCont = new CookieContainer();

        public string CreateGet(string url)
        {
            HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create(url);
            request.CookieContainer = cookieCont;
            try
            {
                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    using (var st = response.GetResponseStream())
                    {
                        var reader = new StreamReader(st, Encoding.UTF8);
                        var result = reader.ReadToEnd();
                        return result;
                    }
                }
            }
            catch
            {
                System.Windows.Forms.MessageBox.Show("Сервер не доступен");
                return null;
            }
        }

        public string CreatePost(string url, string header, string boundary)
        {
            HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create(url);
            request.Method = "POST";
            request.CookieContainer = cookieCont;
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            byte[] h = Encoding.UTF8.GetBytes(header);
            using (var req = request.GetRequestStream())
            {
                req.Write(h, 0, h.Length);
                try
                {
                    using (var response = (HttpWebResponse)request.GetResponse())
                    {
                        using (var st = response.GetResponseStream())
                        {
                            var reader = new StreamReader(st, Encoding.UTF8);
                            var result = reader.ReadToEnd();
                            return result;
                        }
                    }
                }
                catch
                {
                    System.Windows.Forms.MessageBox.Show("Сервер не доступен");
                    return null;
                }
            }
        }

        public int CreatePostWithFile(string url, string header, string pathToFile, string boundary)
        {
            HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create(url);
            request.Timeout = 50000;
            request.Method = "POST";
            request.CookieContainer = cookieCont;
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            byte[] h = Encoding.UTF8.GetBytes(header);
            using (var req = request.GetRequestStream())
            {
                req.Write(h, 0, h.Length);

                //Добавление файла к форме отправки
                FileStream myFile = null;
                try
                {
                    myFile = new FileStream(pathToFile, FileMode.Open, FileAccess.Read);
                }
                catch
                {
                    if (myFile != null) myFile.Close();
                    System.Windows.Forms.MessageBox.Show("Ошибка открытия файла " + Path.GetFileName(pathToFile));
                    return UploadStatus.Unknown.GetHashCode();
                }
                using (BinaryReader myReader = new BinaryReader(myFile))
                {
                    byte[] buffer = myReader.ReadBytes(2048);
                    while (buffer.Length > 0)
                    {
                        req.Write(buffer, 0, buffer.Length);
                        buffer = myReader.ReadBytes(2048);
                    }
                }
                //string endLine = "\n--" + boundary + "\n" + 	AppFuscator.exe!AppFuscator.SettingForm.StartUpload() Строка 44 + 0x43 байт	C#

                //                 "Content-Disposition: form-data; name=\"Upload\"\n\nSubmit Query";
                string endLine = "\n--" + boundary + "--";
                byte[] e = Encoding.UTF8.GetBytes(endLine);
                req.Write(e, 0, e.Length);
                try
                {
                    using (var response = (HttpWebResponse)request.GetResponse())
                    {
                        using (var st = response.GetResponseStream())
                        {
                            var reader = new StreamReader(st, Encoding.UTF8);
                            var result = reader.ReadToEnd();

                            JObject responseData = Utils.ParseJson(result);
                            if (response == null || responseData.Property("state") == null)
                                throw new Exception();
                            else
                                return int.Parse(responseData.Property("state").Value.ToString());

                        }
                    }

                }
                catch
                {

                    System.Windows.Forms.MessageBox.Show("Сервер не доступен");
                    return UploadStatus.Unknown.GetHashCode();
                }
            }
        }

        public void RessetSession()
        {
            cookieCont = new CookieContainer();
        }
    }
}